import pymysql


class DbUtil:
    # 定义全局变量
    conn = None

    # 建立conn
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2021",
                                   database="ihrm", charset="utf8")
        return cls.conn

    # 关闭conn
    @classmethod
    def __close_db(cls):
        cls.conn.close()

    # 查询语句
    @classmethod
    def get_one(cls, sql):
        # 定义游标变量
        cursor = None
        try:
            # 创建conn
            cls.conn = cls.__connect_db()
            # 创建cursor
            cursor = cls.conn.cursor()
            # 执行sql
            cursor.execute(sql)
            result = cursor.fetchone()

        except Exception as err:
            print("查询数据库操作错误:", str(err))
        finally:
            # 关闭cursor
            cursor.close()
            # 关闭conn
            cls.__close_db()
            return result

    # 增删改语句
    @classmethod
    def uid_db(cls, sql):

        cursor = None
        try:
            cls.conn = cls.__connect_db()
            # 创建cursor
            cursor = cls.conn.cursor()
            # 执行sql
            cursor.execute(sql)
            # 事务提交/回滚
            cls.conn.commit()
            affect_row = cls.conn.affected_rows()
            print("影响的行数=", affect_row)

        except Exception as err:
            print("增删改错误日志=", str(err))
            cls.conn.rollback()
        finally:
            # 关闭cursor
            cursor.close()
            # 关闭conn
            cls.__connect_db()

